//
//  myParser.m
//  exam_json
//
//  Created by WOONGJIN HWANG on 11/09/13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "myParser.h"
#import "JSON.h"

#define URL_STRING @"http://maps.googleapis.com/maps/api/geocode/json?address="
#define TEXT_VAR @"&sensor=true"

@implementation myParser

- (NSString*)translateText:(NSString*)sourceText {
    //    NSString* urlString = @"http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    // problem with japanese-space
    NSMutableString* urlString = [NSMutableString string];
    NSString* convert1 = @"江東区　区役所";
    NSString* convert = [convert1 stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    [urlString appendString:URL_STRING];
    [urlString appendString:[convert stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [urlString appendString:TEXT_VAR];
    NSLog(@"urlString = %@",urlString);

	NSURL* url = [NSURL URLWithString: urlString];
	NSURLRequest* request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 60.0];
	NSURLResponse* response; NSError* error;
	NSData* data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
	if (data == nil) {
		NSLog(@"Could not connect to the server: %@ %@", urlString, [error description]);
		return nil;
	} else {
		NSString* contents = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] ;
		SBJsonParser *parser = [[SBJsonParser alloc] init];
        
        
        NSDictionary *object = [parser objectWithString:contents error:nil];
        
        NSArray *notes = [object valueForKey:@"results"];
        for (NSDictionary *singleNote in notes){
            NSString *lat = [[[singleNote objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lat"];
            NSString *lng = [[[singleNote objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lng"];
            
            NSLog(@"lat: %@",lat);
            NSLog(@"lng: %@",lng);
        }
        self.Data2JSON;

    }
    return urlString;
}

-(void)Data2JSON {
    NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"hoge", @"name",
                                    @"999-9999-9999", @"tel",
                                    @"東京都", @"address", nil];
    SBJsonWriter *jsonWriter = [SBJsonWriter new];
    //Just for error tracing
    jsonWriter.humanReadable = YES;
    NSString *json = [jsonWriter stringWithObject:jsonDictionary];
    NSLog(@"first json = %@",json);
    if (!json){
        NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]);
    }
    [jsonWriter release];
    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"json = %@",data.description);

}

@end
